import axios from 'axios'
import {Message} from 'element-ui'
import store from '../store'
import {getToken,removeToken} from '@/utils/auth'
import Qs from 'qs'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 15000,                  // 请求超时时间
  transformRequest: [function (data) {
    data = Qs.stringify(data);
    return data;
  }]
})

// request拦截器
service.interceptors.request.use(config => {

  if (!config.params) {
    config.params = {}
  }

  config.params.responseType = 'json'




  if (store.getters.token) {

    config.params.uuid = store.getters.token
    config.params.userid = store.getters.userId

  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {

    //console.log('response',response)


    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data

    //console.log('res.statusCode',res.statusCode)

    if(res.statusCode == 401){

      removeToken()

    }else if (res.statusCode != 200) {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject('error')
    } else {
      return response.data
    }



    return response.data;

  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
